package com.cxps.cloud.utils;

import com.cxps.cloud.common.CustomUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * JWT Token工具类
 *
 * @author YouCai.Liu
 * @since 2021/10/24
 * ...
 */
@Slf4j
@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";
    private static final String CLAIM_KEY_AUTH = "auth";

    // token私钥
    private static String PRIVATE_KEY = "mySecret";

    /**
     * 根据用户信息生成Token
     *
     * @param user
     * @return
     */
    public static String generateToken(CustomUser user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, user.getUserName());
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_AUTH, user.getAuthorities());
        return generateToken(claims);
    }

    /**
     * 生成JWT的Token
     *
     * @param claims 要放进JWT里的信息
     * @return
     */
    private static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                // 信息
                .setClaims(claims)
                // 过期时间
                .setExpiration(generateExpirationDate())
                // 加密算法和私钥
                .signWith(SignatureAlgorithm.HS512, PRIVATE_KEY)
                .compact();
    }

    /**
     * 从Token中获取登录用户名
     */
    public static String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 从Token中获取JWT中的负载
     */
    public static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(PRIVATE_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成Token的过期时间
     */
    private static Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000);
    }

    /**
     * 验证Token是否还有效
     *
     * @param token    客户端传入的token
     * @param userName springSecurity中的用户信息
     */
    public static boolean validateToken(String token, String userName) {
        String username = getUserNameFromToken(token);
        return username.equals(userName) && !isTokenExpired(token);
    }

    /**
     * 判断Token是否已经失效
     */
    public static boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从Token中获取过期时间
     */
    private static Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 判断Token是否可以被刷新
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }

    /**
     * 刷新Token
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    public static void main(String[] args) {

        JwtTokenUtil.PRIVATE_KEY = "123456";
        CustomUser user = new CustomUser();
        user.setUserName("Admin2");
        user.setAuthorities(Arrays.asList("ADMIN", "USER"));

        String token = generateToken(user);
        System.out.println("--下面就是生产的Token：");
        System.out.println(token);

        String username = getUserNameFromToken(token);
        System.out.println("--从Token获取信息：");
        System.out.println(username);

        Claims claimsFromToken = getClaimsFromToken(token);
        System.out.println(claimsFromToken);
        System.out.println(claimsFromToken.getSubject());
        System.out.println(claimsFromToken.get("auth"));
        System.out.println(claimsFromToken.get("created"));

    }
}
